﻿using AuthCenter.API.Application.Command.Request;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Account;
using AuthCenter.Domain.Request;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;

namespace AuthCenter.API.Application.Handler.Request
{
    public class GetRequestHandler : IRequestHandler<GetRequestCommand, APIPaging<RequestModel>>
    {
        private readonly IBaseRepository<RequestModel> requestRepo;
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<AccountRoleModel> accountRoleRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public GetRequestHandler(IBaseRepository<RequestModel> requestRepo,
                                IBaseRepository<AccountModel> accountRepo,
                                IBaseRepository<AccountRoleModel> accountRoleRepo,
                                IBaseRepository<RoleModel> roleRepo,
                                IMapper mapper)
        {
            this.requestRepo = requestRepo;
            this.accountRepo = accountRepo;
            this.accountRoleRepo = accountRoleRepo;
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<APIPaging<RequestModel>> Handle(GetRequestCommand request, CancellationToken cancellationToken)
        {
            APIPaging<RequestModel> result = new APIPaging<RequestModel>();
            var res = requestRepo.GetAll().Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.ApplicantName))
            {
                res = res.Where(x => x.ApplicantName.Contains(request.ApplicantName));
            }
            if (request.State.HasValue)
            {
                res = res.Where(x => x.State == request.State);
            }
            if (request.StartTime != null)
            {
                res = res.Where(x => x.StartTime >= request.StartTime || x.EndTime >= request.StartTime);
            }
            if (request.EndTime != null)
            {
                res = res.Where(x => x.StartTime <= request.EndTime || x.EndTime <= request.EndTime);
            }
            if (request.LoginName != null)
            {
                res = res.Where(x => x.ApplicantName == request.LoginName || x.DepartmentHead == request.LoginName);
            }
            result.TotalCount = res.Count();
            result.TotalPage =(int)Math.Ceiling(result.TotalCount*1.0/request.TotalSize);
            result.PageDatas = res.OrderByDescending(x => x.CreateDate).Skip((request.PageIndex - 1) * request.TotalSize).Take(request.TotalSize).Distinct().ToList();
            return Task.FromResult(result);
        }
    }
}

